package xyz.dava.sync.fm.config;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory;

@Configuration
public class MongoConfig {
    @Bean
    @Primary
    @ConfigurationProperties(prefix="spring.data.mongodb")
    public MongoProperties mongoProperties() {
        return new MongoProperties();
    }

    @Primary
    @Bean
    public MongoTemplate mongoTemplate() throws Exception {
        return new MongoTemplate(mongoDatabaseFactory(mongoProperties()));
    }

    @Bean
    @Primary
    public MongoDatabaseFactory mongoDatabaseFactory(MongoProperties mongoProperties) throws Exception {
        return new SimpleMongoClientDatabaseFactory(mongoProperties.getUri());
    }

    @Bean
    @ConfigurationProperties(prefix="spring.data.old.mongodb")
    public MongoProperties oldMongoProperties() {
        return new MongoProperties();
    }

    @Bean
    public MongoTemplate oldMongoTemplate() throws Exception {
        return new MongoTemplate(oldMongoDatabaseFactory(oldMongoProperties()));
    }

    @Bean
    public MongoDatabaseFactory oldMongoDatabaseFactory(
            @Qualifier("oldMongoProperties") MongoProperties mongoProperties) throws Exception {
        return new SimpleMongoClientDatabaseFactory(mongoProperties.getUri());
    }


    @Bean
    @ConfigurationProperties(prefix="spring.data.local.mongodb")
    public MongoProperties localMongoProperties() {
        return new MongoProperties();
    }

    @Bean
    public MongoTemplate localMongoTemplate() throws Exception {
        return new MongoTemplate(localMongoDatabaseFactory(localMongoProperties()));
    }

    @Bean
    public MongoDatabaseFactory localMongoDatabaseFactory(
            @Qualifier("localMongoProperties") MongoProperties mongoProperties) throws Exception {
        return new SimpleMongoClientDatabaseFactory(mongoProperties.getUri());
    }

}
